import { Layout } from "@/components/layout/layout";
import withAuth, { getServerSideProps } from "@/hoc/withAuth";
import { useHttp } from "@/hooks";
import useMounted from "@/hooks/useMounted";
import type { NextPage, GetServerSidePropsContext } from "next";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import React from "react";
import {
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  getKeyValue,
  Button,
  Image,
  Chip,
  Avatar,
  Link,
} from "@nextui-org/react";
import { User } from "@/entities/User";
import { capitalize } from "@/utils/base";
import dayjs from "dayjs";
import EndpointModal from "@/components/modal/endpointModal";
import { App } from "@/entities/App";
import { Dataset } from "@/entities/Dataset";
import { Endpoint } from "@/entities/Endpoint";
import ConfirmModal from "@/components/modal/confirmModal";
import {
  Add,
  AddBoxOutlined,
  AddCircleOutline,
  AddSharp,
  BlockSharp,
  CheckCircleOutline,
} from "@mui/icons-material";
import { showToast } from "@/components/toast";

const EndpointsPage: NextPage = () => {
  const [endpoints, setEndpoints] = useState<Endpoint[]>([]);
  const [visible, setVisible] = useState(false);
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [confirmMsg, setConfirmMsg] = useState("");
  const router = useRouter();
  const { datasetid } = router.query;

  const { http } = useHttp();
  const [curEndpointId, setCurEndpointId] = useState<number>();

  const getEndpointList = async (silent = false) => {
    const res = await http.get(
      "/api/endpoint/list",
      { datasetid },
      { isOpenLoading: true, silent }
    );
    if (res?.success) {
      setEndpoints(res.data.endpoints as Endpoint[]);
    }
  };

  const getEndpointListRef = useRef(getEndpointList);

  useMounted(() => {
    getEndpointListRef.current();
  });

  const cols = [
    "id",
    "name",
    "type",
    "introduce",
    "value",
    "dataset",
    "editor",
    "updatedAt",
    "operation",
  ];
  const columns = cols.map((col) => ({
    key: col,
    label:
      col == "isDelete" ? "Status" : capitalize(col.replace(/[A-Z]/g, " $&")),
  }));

  const getVal = (item: Endpoint, key: string | number) => {
    // debugger;
    const val = getKeyValue(item, key);
    if (key === "dataset") {
      const dataset = val as Dataset;
      return (
        <Chip size="sm" color={"success"} variant="flat">
          {dataset.name}
        </Chip>
      );
    } else if (key === "name") {
      return val;
      // return (
      //   <Link color="primary" href={`/configs?appid=${item.id}`}>
      //     {val}
      //   </Link>
      // );
    } else if (["createdAt", "updatedAt"].includes(key.toString())) {
      const day = dayjs(val).format("YYYY-MM-DD HH:mm:ss");
      return day;
    } else if (key === "editor") {
      const editor = val as User;
      return (
        <Chip
          size="sm"
          startContent={
            <Avatar
              className="w-4 h-4"
              name={editor.name}
              src={editor.avatarData}
            />
          }
          color={"success"}
          variant="flat"
        >
          {editor.name}
        </Chip>
      );
    } else {
      return val;
    }
  };

  const onCreated = (success: boolean) => {
    success && getEndpointListRef.current(true);
  };

  const handleEdit = (id: number) => {
    setCurEndpointId(id);
    setVisible(true);
  };

  const handleDel = (item: Endpoint) => {
    setCurEndpointId(item.id);
    setConfirmMsg(`Delete endpoint "${item.name}"?`);
    setConfirmModalVisible(true);
  };

  const onDelete = async () => {
    const res = await http.post(
      "/api/endpoint/delete",
      { endpointid: curEndpointId },
      { isOpenLoading: true }
    );
    if (res?.success) {
      getEndpointListRef.current(true);
    }
  };

  return (
    <div className="datasets-page px-6 py-3">
      <EndpointModal
        mode="edit"
        visible={visible}
        closeCallback={() => setVisible(false)}
        endpointId={curEndpointId}
        confirmCallback={onCreated}
      />

      <ConfirmModal
        title="Confirm"
        message={confirmMsg}
        visible={confirmModalVisible}
        closeCallback={() => setConfirmModalVisible(false)}
        confirmCallback={onDelete}
      />

      <div className="actions text-right mb-4">
        <EndpointModal mode="create" confirmCallback={onCreated} />
      </div>
      <Table className="text-center" aria-label="apps table">
        <TableHeader columns={columns}>
          {(column) => (
            <TableColumn
              className="text-center"
              align="end"
              allowsResizing
              key={column.key}
            >
              {column.label}
            </TableColumn>
          )}
        </TableHeader>
        <TableBody items={endpoints} emptyContent="no data">
          {(item) => (
            <TableRow key={item.id}>
              {(columnKey) =>
                columnKey === "operation" ? (
                  <TableCell>
                    <Button
                      variant="flat"
                      className="m-2 rounded-md"
                      size="sm"
                      color="primary"
                      onClick={() => handleEdit(item.id)}
                    >
                      Edit
                    </Button>
                    <Button
                      variant="flat"
                      className="m-2 rounded-md"
                      size="sm"
                      color="danger"
                      onClick={() => handleDel(item)}
                    >
                      Del
                    </Button>
                  </TableCell>
                ) : (
                  <TableCell>{getVal(item, columnKey)}</TableCell>
                )
              }
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};

export { getServerSideProps };

export default withAuth(EndpointsPage);
